//
//  LBHorizontalTextLoopView.m
//  LBHorizontalTextLoopView
//
//  Created by Apple on 2021/9/20.
//

#import "LBHorizontalTextLoopView.h"
#import "CADisplayLink+LBHelper.h"

@interface LBHorizontalTextLoopView () <UIScrollViewDelegate>

///计时器
@property (nonatomic, strong) CADisplayLink *linker;
///滚动视图
@property (nonatomic, strong) UIScrollView *scrollview;
///有计时器
@property (nonatomic, assign) BOOL hasLinker;
///文案数组
@property (nonatomic ,strong) NSArray <NSString *> *contentArray;


@end

@implementation LBHorizontalTextLoopView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.textColor = [UIColor whiteColor];
        self.font = [UIFont systemFontOfSize:12];
        self.velocity = 0.75;
        [self setUpUI];
    }
    return self;
}

- (void)setUpUI
{
    self.scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
    [self addSubview:self.scrollview];
    self.scrollview.contentSize = CGSizeMake(self.bounds.size.width, self.bounds.size.height);
    self.scrollview.delegate = self;
    self.scrollview.scrollEnabled = NO;
    self.scrollview.showsHorizontalScrollIndicator = NO;
}

#pragma mark - 展示数据
- (void)loadWithContentArray:(NSArray <NSString *> *)contentArray
{
    if ([contentArray isEqualToArray:_contentArray]) {
        return;
    }
    if (self.superview && CGSizeEqualToSize(self.scrollview.bounds.size, CGSizeZero)) {
        //初始化没有设置scrollviewFrame 的时候需要更新 scrollview的frame
        [self.superview layoutIfNeeded];
        self.scrollview.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    }
    _contentArray = contentArray;
    NSMutableArray *marray = [NSMutableArray array];
    //为达到循环轮播的效果添加三个相同数组
    [marray addObjectsFromArray:contentArray];
    [marray addObjectsFromArray:contentArray];
    [marray addObjectsFromArray:contentArray];
    [self.scrollview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self showContentWithArray:marray.copy];
}

- (void)showContentWithArray:(NSArray *)array
{
    CGFloat x = 0;
    NSInteger i = 0;
    
    for (NSString *string  in array)
    {
        CGFloat width = [string boundingRectWithSize:CGSizeMake(100000, 16) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: self.font} context:nil].size.width + 40;
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:string forState:UIControlStateNormal];
        button.titleLabel.font = self.font;
        button.titleEdgeInsets = UIEdgeInsetsMake(button.titleEdgeInsets.top, 0, button.titleEdgeInsets.bottom, button.titleEdgeInsets.right + button.titleEdgeInsets.left);
        [button setTitleColor:self.textColor forState:UIControlStateNormal];
        button.frame = CGRectMake(x, 0, width, self.bounds.size.height);
        button.tag = 300 + i;
        
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollview addSubview:button];
        
        
        x += width;
        if (i == array.count/3 - 1) {
            /// array.cont/3 -1 时最后一条文案的索引序号
            //如果所有的消息加到一起都没有scrollview宽度长，则不轮播
            if (CGRectGetMaxX(button.frame) < self.scrollview.bounds.size.width) {
                [self stopScroll];
                self.hasLinker = NO;
                break;
            }
        }
        
       if (i == array.count - 1) {
            self.scrollview.contentSize = CGSizeMake(CGRectGetMaxX(button.frame), self.bounds.size.height);
            [self.scrollview setContentOffset:CGPointZero animated:NO];
        }
        if (i == array.count - 1) {
            if (!_linker) {
                [self startScroll];
            }
        }
        
        i++;
    }
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x > scrollView.contentSize.width/3.0 * 2) {
        [self.scrollview setContentOffset:CGPointMake(scrollView.contentSize.width/3.0 + (scrollView.contentOffset.x - scrollView.contentSize.width/3.0 * 2), 0) animated:NO];
    }
}


#pragma mark - 滚动处理

- (void)startDisplayLink
{
    if (self.hasLinker && !_linker) {
        [self startScroll];
    }
}

- (void)stopScroll
{
    if (_linker) {
        [_linker invalidate];
        _linker = nil;
    }
}

- (void)startScroll {
    self.linker = [CADisplayLink lb_displayLinkWithTarget:self selector:@selector(displayLinkAction)];
    [self.linker addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    self.hasLinker = YES;
}

- (void)displayLinkAction
{
    
    [self.scrollview setContentOffset:CGPointMake(self.scrollview.contentOffset.x + self.velocity, 0)];
}

#pragma mark - action
- (void)click:(UIButton *)sender
{
    NSInteger tag = (sender.tag - 300) % _contentArray.count;
    if (self.delegate && [self.delegate respondsToSelector:@selector(horizontalLoopViewdidSelectItemAtIndex:)]) {
        [self.delegate horizontalLoopViewdidSelectItemAtIndex:tag];
    }
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
